package com.elangzhi.ssm.tools;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 网络访问工具类
 */
public class HttpUtil {

    public static void main(String[] args) {
        JSONObject jsonObject = get("http://120.27.120.27:8080/app/user/login?userName=18660132803&password=123456");
        System.out.println(jsonObject.toJSONString());
        System.out.println(jsonObject.getBoolean("success"));
/*        JSONObject jsonObject1 = get("http://a094.abc123rt.com/index.php?s=/Api/Userapi/login/username/intel1234/password/123456");
        System.out.println(jsonObject1.getBoolean("status"));
        System.out.println(jsonObject1.getString("msg"));
        System.out.println(jsonObject1.getString("data"));*/
    }

    /**
     * 执行get请求
     * @param url 请求地址
     */
    public static JSONObject get(String url){
        try {

            CloseableHttpClient client= HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(5000)
                    .build();
            get.setConfig(requestConfig);
            CloseableHttpResponse response=client.execute(get);
            String value = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JsonUtil.stringToJSONObject(value);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
